// index.js
const db = wx.cloud.database()

Page({
    data: {
        uid: "bc8e764297af64e3edecedfaab6db75c",//用户密钥，巴法云控制台获取
        cardtopic: "CardId",//控制led的主题，创客云控制台创建
        usertopic: "UserData",//传输温湿度的主题，创客云控制台创建
        rmb: '',
        recorddata: "a#b#a#b#a#b#a#b#a#b",
        userdata: "a#b#a#b#a#b#a#b#a#b",
        cardIDnum: ["ed8aa8ab6442b033001268fb6c37d43e", "0122a5876447afe209d9b4f341e754e2", "2cc84e266447b07d09e223a04b9a4dd4", "627d94766447c3b50014bbb81bb28c6c"],
        cardID: ["0006063293", "0013811701", "0013806729", "0000000000"],
        numID: ['1号柜', '2号柜', '3号柜', '4号柜', '5号柜'],
    },
    onLoad: function (options) {
        this.getuserdataInit()
        this.getrecorddataInit()
        setInterval(this.getrecorddataAll, 3000)
        setInterval(this.getuserdataAll, 2400)
        this.getrmb()
    },
    getuserdataInit() {
        var that = this
        //获取温湿度值，屏幕初始化时，未订阅收到温湿度时，先去主动获取值
        //api 接口详细说明见巴法云接入文档
        wx.request({
            url: 'https://api.bemfa.com/api/device/v1/data/1/get/', //状态api接口，详见巴法云接入文档
            data: {
                uid: that.data.uid,
                topic: that.data.usertopic,
                num: 1
            },
            header: {
                'content-type': "application/x-www-form-urlencoded"
            },
            success(res) {
                if (that.data.userdata === res.data.msg) {
                }
                else {
                    //如果有#就进行字符串分割
                    var user_data_arr = that.data.userdata.split("#");
                    var all_data_arr = res.data.msg.split("#"); //分割数据，并把分割后的数据放到数组里。
                    that.setData({ //数据赋值给变量
                        userdata: res.data.msg
                    })
                    for (var i = 0; i < 5; i++) {
                        if (((all_data_arr[(2 * i)]) === user_data_arr[(2 * i)]) && ((all_data_arr[(2 * i + 1)]) === user_data_arr[(2 * i + 1)])) {
                        } else {
                            for (var n = 0; n < 4; n++) {
                                if (that.data.cardID[n] === all_data_arr[(2 * i + 1)]) {
                                    break;
                                }
                            }
                            var state = true;
                            if (all_data_arr[(2 * i)] === "1") {
                                state = true;
                            }
                            else {
                                state = false;
                            }
                            db.collection("Udata").where({ num: that.data.numID[i] }).update({
                                data: {
                                    state: state,
                                    user: that.data.cardIDnum[n]
                                },
                            })
                        }
                    }
                }
            }
        })
    },
    getuserdataAll() {
        var that = this
        //更新刷卡数据
        wx.request({
            url: 'https://api.bemfa.com/api/device/v1/data/1/get/', //状态api接口，详见巴法云接入文档
            data: {
                uid: that.data.uid,
                topic: that.data.usertopic,
                num: 1
            },
            header: {
                'content-type': "application/x-www-form-urlencoded"
            },
            success(res) {
                if (that.data.userdata === res.data.msg) {
                }
                else {
                    //如果有#就进行字符串分割
                    var user_data_arr = that.data.userdata.split("#");
                    var all_data_arr = res.data.msg.split("#"); //分割数据，并把分割后的数据放到数组里。
                    that.setData({ //数据赋值给变量
                        userdata: res.data.msg
                    })
                    for (var i = 0; i < 5; i++) {
                        if (((all_data_arr[(2 * i)]) === user_data_arr[(2 * i)]) && ((all_data_arr[(2 * i + 1)]) === user_data_arr[(2 * i + 1)])) {
                        } else {
                            for (var n = 0; n < 4; n++) {
                                if (that.data.cardID[n] === all_data_arr[(2 * i + 1)]) {
                                    break;
                                }
                            }
                            var state = true;
                            if (all_data_arr[(2 * i)] === "1") {
                                state = true;
                            }
                            else {
                                state = false;
                            }
                            db.collection("Udata").where({ num: that.data.numID[i] }).update({
                                data: {
                                    state: state,
                                    user: that.data.cardIDnum[n]
                                },
                            })
                            break;
                        }
                    }
                }
            }
        })
    },
    getrecorddataInit() {
        var that = this
        //获取温湿度值，屏幕初始化时，未订阅收到温湿度时，先去主动获取值
        //api 接口详细说明见巴法云接入文档
        wx.request({
            url: 'https://api.bemfa.com/api/device/v1/data/1/get/', //状态api接口，详见巴法云接入文档
            data: {
                uid: that.data.uid,
                topic: that.data.cardtopic,
                num: 1
            },
            header: {
                'content-type': "application/x-www-form-urlencoded"
            },
            success(res) {
                that.setData({
                    recorddata: res.data.msg
                })
            }
        })
    },
    getrecorddataAll() {
        var that = this
        var id = ''
        //更新历史记录
        wx.request({
            url: 'https://api.bemfa.com/api/device/v1/data/1/get/', //状态api接口，详见巴法云接入文档
            data: {
                uid: that.data.uid,
                topic: that.data.cardtopic,
                num: 1
            },
            header: {
                'content-type': "application/x-www-form-urlencoded"
            },
            success(res) {
                if (that.data.recorddata === res.data.msg) {
                }
                else {
                    console.log(res.data.msg)
                    that.setData({
                        recorddata: res.data.msg
                    })
                    var all_data_arr = res.data.msg.split("#"); //分割数据，并把分割后的数据放到数组里。
                    let num = parseInt(all_data_arr[2])
                    num += 1
                    if (all_data_arr[1] === 'a') {
                        db.collection("userdata").where({ cardID: all_data_arr[0] }).get().then(res => {
                            db.collection("record").add({
                                data: {
                                    num: num,
                                    cardID: all_data_arr[0],
                                    name: res.data[0].name,
                                    state: 0,
                                    _createTime: Date.parse(new Date()),
                                    _updateTime: Date.parse(new Date()),
                                }
                            })
                        })
                    }
                    else {
                        db.collection("record").where({ cardID: all_data_arr[0] }).orderBy('_createTime', 'desc').get().then(res => {
                            console.log(res.data[0])
                            id = res.data[0]._id
                            if (id == '') {
                            }
                            else {
                                db.collection("record").doc(id).update({
                                    data: {
                                        state: 1,
                                        _updateTime: Date.parse(new Date()),
                                    },
                                })
                            }

                            // db.collection("record").where({ _id: id }).update({
                            //     data: {
                            //         time: time,
                            //     },
                            // })
                        })
                    }
                }
            }
        })
    },
    getrmb() {
        wx.cloud.callFunction({
            name: 'getuserdata',
            complete: res => {
                this.setData({
                    rmb: res.result.list
                })
            }
        })
    },
    onPullDownRefresh: function () {
        var that = this
        //导航条加载动画
        wx.showNavigationBarLoading()
        //loading 提示框
        wx.showLoading({
            title: 'Loading...',
        })
        console.log("下拉刷新啦");
        setTimeout(function () {
            that.getrmb()
            wx.hideLoading();
            wx.hideNavigationBarLoading();
            //停止下拉刷新
            wx.stopPullDownRefresh();
        }, 2000)
    },
});
